//
//  Created by inno on 11/12/11.
//
// To change the template use AppCode | Preferences | File Templates.
//


#import "LoginRequest.h"
#import "UrlBuilder.h"


@implementation LoginRequest

- (NSString *)getUrl {
    UrlBuilder *builder = [UrlBuilder new];
    builder.baseUrl = [self url];
    builder.action = @"login";
    [builder addArgument:@"username" with:[self username]];
    [builder addArgument:@"password" with:[self password]];
    return [builder getUrl];
}

- (void)send {
    NSURL *url = [NSURL URLWithString:[self getUrl]];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                            timeoutInterval:60.0];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        receivedData = [[NSMutableData data] retain];
    } else {
        NSLog(@"connection failed");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // It can be called multiple times, so each time we reset the data.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed! Error - %@ %@",
            [error localizedDescription],
            [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]);
    NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSLog(dataString);
    NSDictionary *results = [dataString JSONValue];
    NSLog(@"%@", results);
}

@end